<template>
  <div class="addtemplate">
    <div class="header">
      <p class="header-title">新增模板</p>
    </div>
    <div class="addtemplate_content">
      <div class="flex-row flex-justify-content-fs flex-align-items-c">
        <p>模板名称:</p>
        <el-input v-model="templateName" placeholder="请输入模板名称" maxlength="16" size="medium "></el-input>
      </div>
      <div class="addtemplate_content_region">
        <div>A区（图片最大尺寸:宽1400*高788，视频少于1分钟，视频小于10MB，资源不少于2个）</div>
        <div class="addtemplate_region_content flex-row">
          <div class="template-a-box flex-row flex-wrap flex-align-items-c">
            <div
              v-for="(item,index) in templateA"
              :key="index"
              class="template-a-item"
              @mouseenter="show(index)"
              @mouseleave="show(index)"
            >
              <img
                v-if="item.name.indexOf('.png') != -1||item.name.indexOf('.jpg') != -1||item.name.indexOf('.jpeg') != -1"
                :src="`${item.url}`"
                alt
              />
              <video v-else :src="`${item.url}`" :id="`video${item.uid}`"></video>
              <div
                v-if="templateA[index].isMaks"
                class="item-mask flex-row flex-align-items-c flex-justify-content-c"
              >
                <i class="el-icon-zoom-in" @click="lookImg(index)"></i>
                <i class="el-icon-delete" @click="delImg(index)"></i>
              </div>
            </div>
            <!--  :before-upload="beforeAvatarUpload" -->
            <el-upload
              :action="uploadActionUrl"
              list-type="picture-card"
              ref="uploadA"
              accept=".mp4, .qlv, .qsv, .ogg, .flv, .avi, .wmv, .rmvb, .png, .jpg, .jpeg"
              :on-preview="handlePictureCardPreview"
              :on-remove="(file, fileList)=>handleRemove(file, fileList,'templateA')"
              :limit="10"
             :multiple='true'
              :file-list="templateA"
              :auto-upload="false"
              :before-upload="beforeAvatarUploadA"
              :on-change="(file, fileList)=>selectedFile(file, fileList,'A')"
              :http-request="uploadCustomizeRequest"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </div>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </div>
      <div class="addtemplate_content_region">
        <div>B区（图片最大尺寸:宽520*高293）</div>
        <div class="addtemplate_region_content">
          <!-- :before-upload="beforeAvatarUpload" -->
          <el-upload
            :action="uploadActionUrl"
            accept=".png, .jpg, .jpeg"
            list-type="picture-card"
            ref="uploadB"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file, fileList)=>handleRemove(file, fileList,'templateB')"
            :limit="2"
            :multiple='true'
            :file-list="templateB"
            :before-upload="beforeAvatarUploadB"
            :auto-upload="false"
            :data="uptoken"
            :http-request="uploadCustomizeRequest"
            :on-change="(file, fileList)=>selectedFile(file, fileList,'B')"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </div>
      </div>
      <div class="my-btn">
        <el-button @click="submitUpload">提交审核</el-button>
      </div>
    </div>
    <!-- <el-progress :percentage="100" status="success"></el-progress> -->
  </div>
</template>

<script>
import { setTimeout } from 'timers'
import * as qiniu from 'qiniu-js'
import { upload } from '../../upload.js'
export default {
  props: {},
  data () {
    return {
      templateName: '',
      dialogImageUrl: '',
      dialogVisible: false,
      templateB: [],
      templateA: [],
      showMaks: false,
      uptoken: {
        token: '',
        key: ''
      },
      qiNiuTokenArr: [],
      uploadActionUrl: 'https://upload.qiniup.com/',
      countNum: 0,
      isFormat: false
    }
  },
  computed: {},
  created () {
    // this.getQNToken();
  },
  mounted () {},
  watch: {},
  methods: {
    handleRemove (file, fileList, template) {
      console.log(file, fileList, template)
      template == 'templateA'
        ? (this.templateA = fileList)
        : (this.templateB = fileList)
    },
    handlePictureCardPreview (file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeAvatarUploadA (file) {
      console.log(file)
      // this.getQNToken(file);
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'video/mp4' ||
        file.type === 'video/qlv' ||
        file.type === 'video/qsv' ||
        file.type === 'video/ogg' ||
        file.type === 'video/flv' ||
        file.type === 'video/avi' ||
        file.type === 'video/wmv' ||
        file.type === 'video/rmvb'
      if (!isJPG) {
        this.$message.error('文件格式错误')
      }
      // const isLt2M = file.size / 1024 / 1024 < 10;
      // if (
      //   (!isLt2M && file.type === "video/mp4") ||
      //   file.type === "video/qlv" ||
      //   file.type === "video/qsv" ||
      //   file.type === "video/ogg" ||
      //   file.type === "video/flv" ||
      //   file.type === "video/avi" ||
      //   file.type === "video/wmv" ||
      //   file.type === "video/rmvb"
      // ) {
      //   this.$message.error("视频大小不能超过 10MB!");
      // }
      // return isJPG && isLt2M;
      const isSize = new Promise(function (resolve, reject) {
        if (
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/jpg'
        ) {
          let width = 1401
          let height = 789
          let _URL = window.URL || window.webkitURL
          let image = new Image()
          image.onload = function () {
            let valid = image.width < width && image.height < height
            console.log(image.width)
            console.log(image.height)
            valid ? resolve() : reject()
          }
          image.src = _URL.createObjectURL(file)
        } else if (
          file.type === 'video/mp4' ||
          file.type === 'video/qlv' ||
          file.type === 'video/qsv' ||
          file.type === 'video/ogg' ||
          file.type === 'video/flv' ||
          file.type === 'video/avi' ||
          file.type === 'video/wmv' ||
          file.type === 'video/rmvb'
        ) {
          resolve()
        }
      }).then(
        () => {
          // this.uptoken.key = file.uid;
          console.log(222222222)
          this.isFormat = true
          return file
        },
        () => {
          this.isFormat = false
          this.$message.error('上传图片尺寸不符合')
          return Promise.reject()
        }
      )
      return isJPG && isSize
    },
    beforeAvatarUploadB (file, fileList) {
      // this.getQNToken(file);
      // console.log(file);
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      // const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.isFormat = false
        this.$message.error('文件格式错误')
      }
      // if (!isLt2M) {
      //   this.$message.error("图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
      const isSize = new Promise(function (resolve, reject) {
        let width = 521
        let height = 294
        let _URL = window.URL || window.webkitURL
        let image = new Image()
        image.onload = function () {
          let valid = image.width < width && image.height < height
          console.log(image.width)
          console.log(image.height)
          valid ? resolve() : reject()
        }
        image.src = _URL.createObjectURL(file)
      }).then(
        () => {
          //   this.uptoken.token = this.qiNiuTokenArr[0].token;
          return file
        },
        () => {
          this.isFormat = false
          console.log('fileList', fileList)
          this.$message.error('上传图片尺寸不符合')
          return Promise.reject()
        }
      )
      return isJPG && isSize
    },
    selectedFile (file, fileList, region) {
      let _this = this
      console.log(file, fileList, region)
      if (region === 'A') {
        const isJPG =
          file.raw.type === 'image/jpeg' ||
          file.raw.type === 'image/png' ||
          file.raw.type === 'image/jpg' ||
          file.raw.type === 'video/mp4' ||
          file.raw.type === 'video/qlv' ||
          file.raw.type === 'video/qsv' ||
          file.raw.type === 'video/ogg' ||
          file.raw.type === 'video/flv' ||
          file.raw.type === 'video/avi' ||
          file.raw.type === 'video/wmv' ||
          file.raw.type === 'video/rmvb'
        const isLt2M = file.size / 1024 / 1024 < 10
        let isTimerVideo = ''
        setTimeout(() => {
          isTimerVideo =
            document.getElementById(`video${file.uid}`).duration / 60 < 1
          // console.log(document.getElementById(`video${file.uid}`).duration/60<2);
          if (
            (!isLt2M &&
              (file.raw.type === 'video/mp4' ||
                file.raw.type === 'video/qlv' ||
                file.raw.type === 'video/qsv' ||
                file.raw.type === 'video/ogg' ||
                file.raw.type === 'video/flv' ||
                file.raw.type === 'video/avi' ||
                file.raw.type === 'video/wmv' ||
                file.raw.type === 'video/rmvb')) ||
            !isTimerVideo
          ) {
            this.$message.error('视频大小不能超过 10MB!时长小于1分钟')
            // if (file.status == "ready") {
            //   this.templateA = [];
            //   this.$refs.uploadA.clearFiles(file);
            // }
            // setTimeout(() => {
            this.templateA = []
            this.$refs.uploadA.clearFiles(file)
            // }, 1000);
          }
        }, 500)
        // console.log(file.size / 1024 / 1024)

        // return isJPG && isLt2M;
        if (!isJPG) {
          this.templateA = []
          this.$refs.uploadA.clearFiles(file)
          this.$message.error('文件格式错误')
        }
        const isSize = new Promise(function (resolve, reject) {
          if (
            file.raw.type === 'image/jpeg' ||
            file.raw.type === 'image/png' ||
            file.raw.type === 'image/jpg'
          ) {
            let width = 1401
            let height = 789
            let _URL = window.URL || window.webkitURL
            let image = new Image()
            image.onload = function () {
              let valid = image.width < width && image.height < height
              console.log(image.width)
              console.log(image.height)
              valid ? resolve() : reject()
            }
            image.src = _URL.createObjectURL(file.raw)
          } else if (
            file.raw.type === 'video/mp4' ||
            file.raw.type === 'video/qlv' ||
            file.raw.type === 'video/qsv' ||
            file.raw.type === 'video/ogg' ||
            file.raw.type === 'video/flv' ||
            file.raw.type === 'video/avi' ||
            file.raw.type === 'video/wmv' ||
            file.raw.type === 'video/rmvb'
          ) {
            resolve()
          }
        }).then(
          () => {
            // this.uptoken.key = file.uid;
            console.log(222222222)
            this.isFormat = true
            this.templateA = fileList
            this.templateA.forEach((el, index) => {
              // console.log(el)
              this.templateA[index].isMaks = false
            })
            return file.raw
          },
          () => {
            this.templateA = []
            this.$refs.uploadA.clearFiles()
            this.isFormat = false
            this.$message.error('上传图片尺寸不符合')
            return Promise.reject()
          }
        )
      } else {
        const isJPG =
          file.raw.type === 'image/jpeg' ||
          file.raw.type === 'image/png' ||
          file.raw.type === 'image/jpg'
        // const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.templateB = []
          this.$refs.uploadB.clearFiles(file)
          this.isFormat = false
          this.$message.error('文件格式错误')
        }
        // if (!isLt2M) {
        //   this.$message.error("图片大小不能超过 2MB!");
        // }
        // return isJPG && isLt2M;
        const isSize = new Promise(function (resolve, reject) {
          let width = 521
          let height = 294
          let _URL = window.URL || window.webkitURL
          let image = new Image()
          image.onload = function () {
            let valid = image.width < width && image.height < height
            console.log(image.width)
            console.log(image.height)
            valid ? resolve() : reject()
          }
          image.src = _URL.createObjectURL(file.raw)
        }).then(
          () => {
            this.templateB = fileList
            //   this.uptoken.token = this.qiNiuTokenArr[0].token;
            return file.raw
          },
          () => {
            this.isFormat = false
            this.templateB = []
            this.$refs.uploadB.clearFiles()
            console.log('fileList', fileList)
            this.$message.error('上传图片尺寸不符合')
            return Promise.reject()
          }
        )
      }
    },
    submitUpload () {
      // let file = this.templateA.length ? this.templateA[0] : this.templateB[0];
      //   if (this.templateA.length) {
      //     for (let i = 0; i < this.templateA.length; i++) {
      //       //   this.getQNToken(this.templateA[i]);
      //       this.getQNToken(this.templateA[i]);
      //       // this.qiNiuTokenArr.shift();
      //       // console.log(this.qiNiuTokenArr);
      //     }
      //   }
      if (
        this.templateName !== '' &&
        this.templateA.length > 1 &&
        this.templateB.length > 0
      ) {
        this.$refs.uploadA.submit()
        this.$refs.uploadB.submit()
      } else {
        this.$message.error('请填写模板名称和上传图片')
      }
    },
    show (index) {
      // console.log(this.templateA[index]);
      let list = this.templateA[index]
      // console.log(list)
      list.isMaks = !this.templateA[index].isMaks
      this.templateA.splice(index, 1, list)
      // this.templateA.splice(indexF, 1, list);
      // this.templateA[index].isMaks = !this.templateA[index].isMaks;
    },
    lookImg (index) {
      this.dialogVisible = !this.dialogVisible
      this.dialogImageUrl = this.templateA[index].url
    },
    delImg (index) {
      this.templateA.splice(index, 1)
    },
    getQNToken (file) {
      console.log('getQNToken', file)
      this.qiNiuTokenArr = []
      let key = file.uid
      let code = `type=advertiserplate&key=${key}`
      console.log(code)
      let RASCODE = this.$getCode(code)
      this.http
        .getQNToken({
          secret: RASCODE
        })
        .then(res => {
          console.log(res)
          if (res.data.errno == '000') {
            // this.uptoken.token = res.data.result.uptoken;
            let qniuToken = {
              token: res.data.result.uptoken,
              key: key
            }
            this.qiNiuTokenArr.push(qniuToken)
          } else {
            this.$message({
              message: res.data.errmsg,
              type: 'warning'
            })
          }
        })
        .then(() => {
          // this.$refs.uploadA.submit();
          // this.$refs.uploadB.submit();
        })
        .catch(err => {})
    },
    uploadCustomizeRequest (request, template) {
      const loading = this.$loading({
        lock: true,
        text: '模板上传中。。。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      console.log('uploadCustomizeRequest', request, template)
      // let key = request.file.uid;
      let key =
        request.file.uid +
        request.file.name.substring(request.file.name.indexOf('.'))
      let code = `type=advertiserplate&key=${key}`
      console.log(code)
      let RASCODE = this.$getCode(code)
      this.http.getQNToken({ secret: RASCODE }).then(res => {
        console.log(res.data.result.uptoken)
        let token = res.data.result.uptoken
        console.log(this.isFormat)
        if (this.isFormat) {
          upload(
            token,
            request,
            next => {
              let total = next.total
              console.log('total', total)
            },
            error => {
              loading.close()
              this.$message.error(error)
              console.log('error', error)
            },
            complete => {
              let hash = complete.hash
              let key = complete.key
              // this.form.url = key;
              console.log('complete', complete)
              console.log('hash', hash)
              console.log('key', key)
              this.countNum++
              console.log('key', this.countNum)
              if (
                this.countNum ==
                  this.templateB.length + this.templateA.length &&
                this.isFormat
              ) {
                let templateA = ''
                let templateB = ''
                this.templateA.forEach((element, index) => {
                  templateA +=
                    this.templateA.length > 1 &&
                    index + 1 < this.templateA.length
                      ? element.uid +
                        element.name.substring(element.name.indexOf('.')) +
                        ','
                      : element.uid +
                        element.name.substring(element.name.indexOf('.'))
                })
                this.templateB.forEach((element, index) => {
                  templateB +=
                    this.templateB.length > 1 &&
                    index + 1 < this.templateB.length
                      ? element.uid +
                        element.name.substring(element.name.indexOf('.')) +
                        ','
                      : element.uid +
                        element.name.substring(element.name.indexOf('.'))
                })
                let code = `advertiser_id=${
                  JSON.parse(sessionStorage.getItem('userinfo')).id
                }&name=${
                  this.templateName
                }&album_a=${templateA}&album_b=${templateB}`
                console.log(code)
                let RASCODE = this.$getCode(code)
                this.http
                  .upAD({ secret: RASCODE })
                  .then(res => {
                    if (res.data.errno == '000') {
                      this.$message.success(res.data.errmsg)
                      loading.close()
                      this.$router.push({
                        path: 'advertising'
                      })
                    } else {
                      loading.close()
                      this.$message.error(res.data.errmsg)
                    }
                  })
                  .catch(err => {
                    console.log(err)
                  })
              }
            }
          )
        } else {
          loading.close()
        }
      })
    }
  },
  components: {}
}
</script>

<style scoped lang="less">
@import url("./index.less");
</style>
<style>
.template-a-box .el-upload-list,
.template-a-box .el-upload-list--picture-card {
  display: none !important;
}
</style>
